package v1

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
)

type Notice struct {
	ID       uint64
	Avatar   string
	Title    string
	Datetime time.Time
	NType    string
}

type Notices []Notice

type User struct {
	ID   uint64 `json:"userid"`
	Name string `json:"name"`
}

type SetPasswordParam struct {
	ID          uint64 `json:"id"`
	NewPassword string `json:"newPassword"`
}

func GetCurrentUser(c *gin.Context) {
	userID := c.MustGet("userID")

	user, err := models.GetUser(userID.(uint64))
	if err != nil {
		log.Println(err)
		c.JSON(http.StatusBadRequest, User{})
		return
	}

	c.JSON(http.StatusOK, User{Name: user.UserName, ID: user.ID})
	return

}

func GetUsers(c *gin.Context) {
	// do a fake
	type Users []interface{}

	c.JSON(http.StatusOK, gin.H{
		"data": make(Users, 0),
	})

}

func GetNotices(c *gin.Context) {
	// do a fake
	c.JSON(http.StatusOK, gin.H{
		"data": make(Notices, 0),
	})
}

func SetPassword(c *gin.Context) {
	userID := c.MustGet("userID").(uint64)
	var newPassword SetPasswordParam
	if err := c.BindJSON(&newPassword); err != nil {
		log.Println(err)
		return
	}

	// check password complexicity
	if err := util.CheckPassword(newPassword.NewPassword); err != nil {
		log.Println(err)
		c.JSON(http.StatusOK, gin.H{
			"status": 10500,
			"data":   err.Error(),
		})
		return
	}

	if err := models.SetPassword(userID, newPassword.NewPassword); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status": 10500,
			"data":   err,
		})
	} else {
		c.JSON(http.StatusOK, gin.H{
			"status": 200,
			"data":   "",
		})
	}
	return
}
